package com.diaohw.module.auth.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.diaohw.module.auth.obj.vo.AccountOnlineVO;
import com.diaohw.module.auth.service.OnlineService;
import com.diaohw.platform.common.obj.page.PageDto;
import com.diaohw.platform.framework.authorization.OnlineManager;
import com.diaohw.platform.framework.redis.util.RedisStringUtil;
import com.diaohw.platform.remote.auth.obj.bo.AccountInfoBO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.diaohw.platform.framework.authorization.OnlineManager.LOGIN_ACCOUNT_INFO;


@Service
public class OnlineImpl implements OnlineService {

    @Resource
    OnlineManager onlineManager;

    @Override
    public List<AccountOnlineVO> list(PageDto page) {
        List<AccountOnlineVO> accounts = onlineManager.online().stream().map(AccountOnlineVO::initial).toList();
        if (accounts.isEmpty()) {
            return List.of();
        }

        return accounts.stream()
                .peek(online -> {
                    AccountInfoBO info = RedisStringUtil.getValue(LOGIN_ACCOUNT_INFO.apply(online.getLoginId()));
                    online.setLoginTime(info.getLoginTime());
                    online.setUsername(info.getAccount().getUsername());
                    online.setNickname(info.getAccount().getNickname());
                })
//                .sorted(Comparator.comparing(AccountOnlineVO::getLoginTime))
                .toList();
    }

    @Override
    public boolean kickOut(String loginId) {
        StpUtil.kickout(loginId);
        onlineManager.logout(loginId);
        return true;
    }

}
